﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Expo.Training.Entity;
using PPTech.ESP.DataProvider;
using Expo.Training.BRule.News;
using Expo.Training.BRule.Access;
using System.Collections.Generic;

public partial class Portal_News_Default : PageBase
{
    public int TotalRsNum
    {
        get
        {
            if (ViewState["TotalRsNum"] == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(ViewState["TotalRsNum"]);
            }
        }
        set
        {
            ViewState["TotalRsNum"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.dv_NoResult.Visible = false;
        if (!IsPostBack)
        {
            InitInputControls();
            BindNews();
        }
    }

    public void DeleteBulletin(int id)
    {
        #region [删除]
        News news = new News();
        news.NID = id;
        if (news.Exist())
        {
          Guid docid = news.DocID;
          Doc_Info objdc = new Doc_Info();
          objdc.DocID = docid;
          if (objdc.Exist())
          {
              DataTable dt = objdc.QueryDataTable();
              string docURL = dt.Rows[0]["DocURL"].ToString();
              string docPDFURL = dt.Rows[0]["DocPDFURL"].ToString();
              string docSWFURL = dt.Rows[0]["DocSWFURL"].ToString();
              string addr1 = "~/" + docURL;
              addr1 = Server.MapPath(addr1);
              System.IO.File.Delete(addr1);
              if (docPDFURL != "")
              {
                  string addr2 = "~/" + docPDFURL;
                  addr2 = Server.MapPath(addr2);
                  System.IO.File.Delete(addr2);
              }
              if (docSWFURL != "")
              {
                  string addr3 = "~/" + docSWFURL;
                  addr3 = Server.MapPath(addr3);
                  System.IO.File.Delete(addr3);
              }

              Doc_Info dc = new Doc_Info();
              dc.DocID = docid;
              dc.Delete();
              dc.Dispose();
          }
        }
        News objNews = new News();
        objNews.NID = id;
        objNews.Delete();
        objNews.Dispose();
        #endregion
    }

    public void btnSearch_ServerClick(object sender, EventArgs e)
    {
        PagerDown.PageIndex = 0;
        BindNews();
    }

    //用户等级集合
    protected Dictionary<Guid, AccessConst.AccessLevel> _memberLevel;
    protected Dictionary<Guid, Expo.Training.BRule.Access.AccessConst.AccessLevel> MemberLevel
    {
        get
        {
            if (_memberLevel == null)
                _memberLevel = new Dictionary<Guid, AccessConst.AccessLevel>();
            return _memberLevel;
        }

    }


    //用户部门操作权限
    protected Dictionary<string, bool> _deptRight;
    protected Dictionary<string, bool> DeptRight
    {
        get
        {
            if (_deptRight == null)
                _deptRight = new Dictionary<string, bool>();
            return _deptRight;
        }

    }

    /// <summary>
    /// 获取用户权限对应值
    /// </summary>
    /// <param name="memberid"></param>
    /// <returns></returns>
    protected AccessConst.AccessLevel GetMemberLevel(Guid memberid)
    {
        if (!MemberLevel.ContainsKey(memberid))
        {
            MemberLevel.Add(memberid, AccessManager.GetMemberAccessLevel(memberid));
        }
        return MemberLevel[memberid];

    }

    protected bool HasRight(Guid currentMember, Guid judgeCreator)
    {
        string key = string.Format("{0}_{1}", currentMember, judgeCreator);
        if (!DeptRight.ContainsKey(key))
        {
            bool right = false;
            // 同一用户有权限
            if (currentMember.Equals(judgeCreator))
            {
                right = true;
            }
            else
            {
                string departId = string.Empty;
                Member_Department objMD = new Member_Department();
                objMD.MemberID = currentMember;
                if (objMD.Exist())
                {
                    departId = objMD.DepartmentID.ToString();
                }
                objMD.Dispose();
                Member_Department objMember = new Member_Department();
                objMember.MemberID = judgeCreator;
                if (objMember.Exist())
                {
                    Department_Info objDepartment = new Department_Info();
                    objDepartment.DepartmentID = objMember.DepartmentID;
                    if (objDepartment.Exist())
                    {
                        // 本部门及子部门的新闻上级管理员都可以进行管理
                        if (objDepartment.KeyString.ToUpper().IndexOf(departId.ToUpper()) > -1)
                        {
                            right = true;
                        }

                    }
                    objDepartment.Dispose();
                }
            }
            DeptRight.Add(key, right);
        }
        return DeptRight[key];

    }
    
    public void Item_Bound(object sender, RepeaterItemEventArgs E)
    {
        #region 绑定 - Repeater Bound
        if (E.Item.ItemIndex == -1)
        {
            return;
        }
        AccessConst.AccessLevel levelID = GetMemberLevel(Member.MemberID);

        if (levelID != Expo.Training.BRule.Access.AccessConst.AccessLevel.System)
        {
            Guid creatorid = new Guid(((HiddenField)(E.Item.FindControl("hid_Creator"))).Value);
            if (creatorid != Guid.Empty)
            {
                Expo.Training.BRule.Access.AccessConst.AccessLevel UserlevelID = GetMemberLevel(creatorid);
                // 如果是系统管理员，直接有删除权限
                if (UserlevelID == Expo.Training.BRule.Access.AccessConst.AccessLevel.System)
                {
                    ((Button)E.Item.FindControl("btn_Delete")).Visible = false;
                }
                else
                {
                    // 如果非系统管理员，则需要判断部门是否包含
                    bool right = HasRight(Member.MemberID, creatorid);
                    if (right)
                    {
                        ((Button)E.Item.FindControl("btn_Delete")).Visible = true;
                        ((HyperLink)E.Item.FindControl("btn_Edit")).Visible = true;
                    }
                    else
                    {
                        ((Button)E.Item.FindControl("btn_Delete")).Visible = false;
                        ((HyperLink)E.Item.FindControl("btn_Edit")).Visible = false;
                    }

                }
            }
        }
        if (E.Item.ItemType == ListItemType.AlternatingItem || E.Item.ItemType == ListItemType.Item)
        {
            ((Button)E.Item.FindControl("btn_Delete")).Attributes.Add("onclick", "return confirm('确定删除吗？');");
        }
        #endregion
    }

    public void Item_Change(object sender, RepeaterCommandEventArgs E)
    {
        #region 绑定 - Repeater Change
        if (E.CommandName == "delete")
        {
            DeleteBulletin(Convert.ToInt32(E.CommandArgument.ToString()));
            Expo.Training.BRule.Audit.Audit.AuditLog(this.Member.MemberID, "新闻管理 - 删除 - ID:" + Convert.ToInt32(E.CommandArgument.ToString()));
        }
        this.BindNews();
        #endregion
    }




    public void BindNews()
    {
        string title = this.txt_title.Text.Trim();
        int type = Convert.ToInt32(this.ddl_newsType.SelectedValue.ToString());
        DateTime beginDate = DateTime.Parse("1900-1-1");
        DateTime endDate = DateTime.Parse("1900-1-1");
        if (this.txt_BeginDate.Text != string.Empty)
        {
             beginDate = DateTime.Parse(this.txt_BeginDate.Text);
        }
        if (this.txt_EndDate.Text != string.Empty)
        {
            endDate = DateTime.Parse(this.txt_EndDate.Text);
        }
        if (endDate < beginDate)
        {
            AddEndScript("","alert('结束时间不能小于开始时间！');");
            return;
        }
        DataTable objTable = BindNewsList(title, type, beginDate, endDate);

        if (objTable.DefaultView.Count <= 0)
        {
            this.dv_list.Visible = false;
            this.dv_NoResult.Visible = true;
            return;
        }
        else
        {
            this.dv_list.Visible = true;
            this.dv_NoResult.Visible = false;
        }
        if (objTable == null)
        {
            return;
        }

        this.rpt_News.DataSource = objTable.DefaultView;
        this.rpt_News.DataBind();

        int total=0;
        Guid rootDepartmentID = AccessManager.GetMemberRootDepartmentID(this.Member.MemberID, this.Member.CustomerID);
        DataTable dt = NewsManager.GetNewsCount(1, 1, out total, rootDepartmentID);
        if (dt != null && dt.Rows.Count>0)
        {
            this.ltNewsCount.Text ="(共"+dt.Rows[0]["number"].ToString()+"条)";
        }
    }

    public DataTable BindNewsList(string title, int type, DateTime beginDate, DateTime endDate)
    {
        int totalCount = 0;
        DataTable dt = NewsManager.GetNewsList(PagerDown.PageIndex + 1, PagerDown.PageSize, out totalCount, type, "AddTime DESC", title, beginDate, endDate, Customer.CustomerID);
        this.rpt_News.DataSource = dt;
        this.rpt_News.DataBind();

        PagerDown.TotalRecords = totalCount;

        ltlTotalThreadDown.Text = totalCount.ToString();

        this.TotalRsNum = PagerDown.CalculateTotalPages();
        if (TotalRsNum < 1)
        {
            TotalRsNum = 1;
        }

        ltlTotalPageDown.Text = this.TotalRsNum.ToString();

        if (this.TotalRsNum <= 1)
        {
            divGoPageDown.Visible = false;
        }

        if (dt.Rows.Count > 0)
        {
            this.divShow.Visible = true;
        }
        else
        {
            this.divShow.Visible = false;
        }
        return dt;
    }

    #region 分页处理
    protected void PagerDown_IndexChanged(object sender, EventArgs e)
    {
        BindNews();
    }
    #endregion

    #region 初始化控件
    private void InitInputControls()
    {
        this.txtGoPageDown.Attributes["onkeydown"] = "if(event.keyCode == 13){event.keyCode = 9;" + ClientScript.GetPostBackClientHyperlink(this.lbtGoPageDown, "") + "}";
    }
    #endregion

    #region 页面跳转处理
    protected void lbtGoPageDown_Click(object sender, EventArgs e)
    {
        int curPage = 0;
        try
        {
            curPage = int.Parse(this.txtGoPageDown.Value.Trim());
        }
        catch
        {
            curPage = 0;
        }
        if (curPage == 0)
            curPage = 1;
        if (curPage > this.TotalRsNum)
            curPage = this.TotalRsNum;
        PagerDown.PageIndex = curPage - 1;
        BindNews();
        this.txtGoPageDown.Value = string.Empty;
    }
    #endregion

    protected string GetAudit(object Status, object IsPass)
    {
        string result = string.Empty;
        int status = Convert.ToInt32(Status);
        int isPass = Convert.ToInt32(IsPass);
        switch (status)
        {
            case 0:
                result = "未请求审核";
                break;
            case 1:
                switch (isPass)
                {
                    case 0:
                        result = "<font color='blue'>待审核</font>";
                        break;
                    case 1:
                        result = "<font color='green'>已通过</font>";
                        break;
                    case 2:
                        result = "<font color='red'>未通过</font>";
                        break;
                }
                break;
        }
        return result;
    }

    public string GetNewsType(string type)
    {
        string strResult = string.Empty;
        switch (type)
        {
            case "1":
                strResult = "慈溪社区快讯";
                break;
            case "11":
                strResult = "慈溪学习公告";
                break;
            case "22":
                strResult = "慈溪图片新闻";
                break;
            case "55":
                strResult = "慈溪时政新闻";
                break;
            case "101":
                strResult = "巴马社区快讯";
                break;
            case "102":
                strResult = "巴马最新公告";
                break;
            case "103":
                strResult = "巴马图片新闻";
                break;
            case "104":
                strResult = "巴马时政新闻";
                break;
        }
        return strResult;
    }
}
